<!--
 saveData() 保存数据的方法

------

 入参：
 flowId： 流程id
 nodeId： 节点id
 flowInstId： 流程实例id
 nodeInstId： 节点实例id
 isOperate:  操作类型  如果是insert，则会查询activity表，保存到 activity inst表中;
                       如果是update，则会查询activity inst表中，保存到 activity inst表中;
                       如果是不填或者其他，则会先去activity inst表中查询是否有对应节点实例的数据，如果有则返回，如果没有，则会去查询activity表，保存方法，会根据查询结果对应保存或者更新到activity inst表中;
-->
<template>
  <div style="position: relative;">
    <div class="tl-form-line-title" v-if="visible" style="display: block; float: left">
      流程活动
    </div>
    <el-button icon="el-icon-edit" type="text" v-if="visible && !disableEdit && disableEditSubmit" style="position: absolute; top: 7px; right: 75px" @click="changeEditState">变更</el-button>
    <el-button icon="el-icon-document-checked" type="text" v-if="visible && !disableEditSubmit" style="position: absolute; top: 7px; right: 15px" @click="tempSaveAll" :loading="saveLoading">保存</el-button>
    <div style="padding-left:15px;" v-if="visible">
      <el-table ref="mainTable" class="tl-table" v-loading="loading" :data="datas" border fit>
        <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
        <el-table-column prop="name" label="名称" width="150px" sortable="custom" sort-by="name" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="introduce" label="活动内容" min-width="200px" sortable="custom" sort-by="introduce" align="left" header-align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="enabled" label="有效" width="140px" align="left" header-align="center">
          <template slot-scope="scope">
            <el-radio-group v-model="scope.row.enabled" :disabled="disableEditSubmit">
              <el-radio :label="parseInt(item.code)" v-for="item in codeModel.enabledList" :key="item.code">{{ item.name }}</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column prop="starttime" label="开始时间" width="160px" align="left" header-align="center">
          <template slot-scope="scope">
            <el-date-picker v-model="scope.row.starttime" type="datetime" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :disabled="disableEditSubmit"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="endtime" label="结束时间" width="160px" align="left" header-align="center">
          <template slot-scope="scope">
            <el-date-picker v-model="scope.row.endtime" type="datetime" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :disabled="disableEditSubmit"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="usercodes" label="参与人员" width="250px" align="left" header-align="center">
          <template slot-scope="scope">
            <tl-ref-user v-model="scope.row.usercodes" :singleSelect="false" dataType="code" :initDisplayData.sync="scope.row.usernames" @confirm="onSelectCboUser($event, scope.row)" :disabled="disableEditSubmit"></tl-ref-user>
          </template>
        </el-table-column>
        <el-table-column prop="place" label="地点" width="200px" align="left" header-align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.place" :disabled="disableEditSubmit"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
/** mixins */
import { mixin_list } from '@tapui/mixins/mixin_list'
import { mixin_approval } from '@tapui/mixins/mixin_approval'
/** 子组件 */
import tlRefUser from '@tapui/components/Tap/Ref/RefUser'
/** 工具类 */
import { getAction, putAction } from '@tapui/utils/http'
import { validateNull } from '@tapui/utils/validate'

/** VUE配置 */
export default {
  mixins: [mixin_list, mixin_approval],
  components: { tlRefUser },
  data() {
    return {
      moduleTitle: '流程活动',
      urlPrefix: '/base/flowActivity/',
      url: {
        // 额外的url
        queryActivity: '/base/flowActivity/queryList',
        queryActivityInst: '/base/flowActivityIns/queryList',
        queryCodeList: '/base/flowCheckItemIns/dataCodeList',
        add: '/base/flowActivityIns/add',
        checkEditState: '/base/flowActivity/checkEditState'
      },
      isQueryOnCreated: false,
      model: {},
      pageInfo: {
        currentPage: 1, // 当前页面
        pageSize: 0, // 每页记录数
        pageSizes: ['10', '50', '100'],
        totalCount: 0 // 总数
      },
      approvalNodeModel: {},
      disableEdit: true,
      disableEditSubmit: false,
      // 是否变更状态
      changeState: false,
      visible: false,
      tableHeight: 0,
      id: '',
      flowid: 0,
      nodeid: 0,
      flowinsid: 0,
      nodeinsid: 0,
      saveLoading: false
    }
  },
  props: {
    render: {
      default: 'div',
      type: String
    },
    // 操作类型
    operate: {
      default: '',
      type: String
    },
    sourceType: {
      default: '',
      type: String
    }
  },
  methods: {
    close() {},
    open() {
      this.disableEdit = this.disableEditSubmit
      this.visible = false
      if (this.approvalNodeModel && this.approvalNodeModel.hasOwnProperty('nodetype')) {
        this.filtersInfo.nodeType = this.approvalNodeModel.nodetype
      }
      // 页面加载完毕执行
      if (this.flowid) {
        this.filtersInfo.flow_id = this.flowid
      }
      if (this.nodeid) {
        this.filtersInfo.node_id = this.nodeid
      }
      if (this.flowinsid) {
        this.filtersInfo.flow_inst_id = this.flowinsid
      }
      if (this.nodeinsid) {
        this.filtersInfo.node_inst_id = this.nodeinsid
      }
      if (this.operate) {
        this.filtersInfo.operate = this.operate
      }
      if (!this.disableEditSubmit) {
        this.url.list = this.url.queryActivity
      } else {
        this.url.list = this.url.queryActivityInst
        // 检查变更按钮是否可用
        this.checkEditState()
      }
      this.loadData()
    },
    resizeHandler() {},
    /** 列表数据加载开始 */
    loadData(paramMap) {
      if (!this.beforeLoadData()) return
      // 查询条件
      var params = this.getQueryParams()
      // 数据查询
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.datas = res.result
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterLoadData()
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    afterLoadData() {
      if (!this.datas || this.datas.length === 0) {
        this.visible = false
        return
      }
      this.visible = true
      this.datas.forEach((item) => {
        if (item.hasOwnProperty('activityname')) {
          item.name = item.activityname
        }
        if (!item.hasOwnProperty('starttime')) {
          this.$set(item, 'starttime', '')
        }
        if (!item.hasOwnProperty('endtime')) {
          this.$set(item, 'endtime', '')
        }
        if (!item.hasOwnProperty('usercodes')) {
          this.$set(item, 'usercodes', '')
        }
        if (!item.hasOwnProperty('place')) {
          this.$set(item, 'place', '')
        }
      })
    },
    asynSave(resolve, reject) {
      if (!this.visible) {
        resolve({ success: true })
        return
      }
      for (let i = 0; i < this.datas.length; i++) {
        if (this.datas[i].hasOwnProperty('enabled') && this.datas[i].enabled === 1) {
          if (!this.datas[i].hasOwnProperty('starttime') || this.datas[i].starttime === null || this.datas[i].starttime === '' || !this.datas[i].hasOwnProperty('endtime') || this.datas[i].endtime === null || this.datas[i].endtime === '' || !this.datas[i].hasOwnProperty('usercodes') || this.datas[i].usercodes === null || this.datas[i].usercodes === '' || !this.datas[i].hasOwnProperty('place') || this.datas[i].place === null || this.datas[i].place === '') {
            reject('请将活动信息补充完整')
            return
          }
          if (this.datas[i].starttime > this.datas[i].endtime) {
            reject('开始时间不允许大于结束时间')
            return
          }
        } else if (this.datas[i].hasOwnProperty('enabled') && this.datas[i].enabled === 0) {
          this.datas[i].starttime = ''
          this.datas[i].endtime = ''
          this.datas[i].usercodes = ''
          this.datas[i].place = ''
        }
      }
      if (!this.flowinsid) {
        reject('流程实例id为空')
      }
      if (!this.nodeinsid) {
        reject('节点实例id为空')
      }
      this.datas.forEach((item) => {
        this.$set(item, 'flowid', this.flowid)
        this.$set(item, 'nodeid', this.nodeid)
        this.$set(item, 'flowinsid', this.flowinsid)
        this.$set(item, 'nodeinsid', this.nodeinsid)
        this.$set(item, 'sourceid', this.id)
        this.$set(item, 'sourcetype', this.sourceType)
        delete item.id
      })
      let paraMap = {}
      this.$set(paraMap, 'listData', this.datas)
      if (this.approvalNodeModel && this.approvalNodeModel.hasOwnProperty('nodetype')) {
        this.$set(paraMap, 'nodeType', this.approvalNodeModel.nodetype)
      }
      if (this.approvalNodeModel && this.approvalNodeModel.hasOwnProperty('sourcetype')) {
        this.$set(paraMap, 'tableName', this.approvalNodeModel.sourcetype)
      }
      this.$set(paraMap, 'workSchedule', 'insert')
      putAction(this.url.add, paraMap).then((res) => {
        resolve(res)
      })
    },
    // 暂存所有活动信息
    tempSaveAll() {
      // 增加活动实例的其他信息
      this.datas.forEach((item) => {
        this.$set(item, 'flowid', this.flowid)
        this.$set(item, 'nodeid', this.nodeid)
        this.$set(item, 'flowinsid', this.flowinsid)
        this.$set(item, 'nodeinsid', this.nodeinsid)
        this.$set(item, 'sourceid', this.id)
        this.$set(item, 'sourcetype', this.sourceType)
        delete item.id
      })
      // 构建发送参数
      let paraMap = {}
      this.$set(paraMap, 'listData', this.datas)
      if (this.approvalNodeModel && this.approvalNodeModel.hasOwnProperty('nodetype')) {
        this.$set(paraMap, 'nodeType', this.approvalNodeModel.nodetype)
      }
      if (this.approvalNodeModel && this.approvalNodeModel.hasOwnProperty('sourcetype')) {
        this.$set(paraMap, 'tableName', this.approvalNodeModel.sourcetype)
      }

      // 若页面为允许编辑状态，增加日程信息
      if (!this.disableEdit) {
        if (!this.changeState) {
          // 非变更状态，不添加日程
          this.$set(paraMap, 'workSchedule', '')
          this.loading = true
          // 发送保存请求
          putAction(this.url.add, paraMap).then((res) => {
            this.loading = false
            if (res.success) {
              this.$tap.message(res.message, 'success')
            } else {
              this.$tap.alert(res.message, 'warning')
            }
          })
        } else {
          // 变更状态，直接添加日程
          // 日程采用更新的过程
          this.$set(paraMap, 'workSchedule', 'update')
          for (let i = 0; i < this.datas.length; i++) {
            if (this.datas[i].hasOwnProperty('enabled') && this.datas[i].enabled === 1) {
              // 若有效性为有效，增加日程信息验证
              if (!this.datas[i].hasOwnProperty('starttime') || this.datas[i].starttime === null || this.datas[i].starttime === '' || !this.datas[i].hasOwnProperty('endtime') || this.datas[i].endtime === null || this.datas[i].endtime === '' || !this.datas[i].hasOwnProperty('usercodes') || this.datas[i].usercodes === null || this.datas[i].usercodes === '' || !this.datas[i].hasOwnProperty('place') || this.datas[i].place === null || this.datas[i].place === '') {
                this.$tap.alert('请将活动信息补充完整', 'warning')
                return
              }
              if (this.datas[i].starttime > this.datas[i].endtime) {
                this.$tap.alert('开始时间不允许大于结束时间')
                return
              }
            } else if (this.datas[i].hasOwnProperty('enabled') && this.datas[i].enabled === 0) {
              // 若有效性为无效，日程信息为空
              this.datas[i].starttime = ''
              this.datas[i].endtime = ''
              this.datas[i].usercodes = ''
              this.datas[i].usernames = ''
              this.datas[i].place = ''
            }
          }
          this.loading = true
          // 发送保存请求
          putAction(this.url.add, paraMap).then((res) => {
            this.loading = false
            if (res.success) {
              this.$tap.message(res.message, 'success')
              this.$set(this, 'disableEditSubmit', true)
              this.$set(this, 'changeState', false)
            } else {
              this.$tap.alert(res.message, 'warning')
            }
          })
        }
      }
    },
    onSelectCboUser(selectedCboUser, scoperow) {
      let userids = ''
      selectedCboUser.forEach((user) => {
        userids += user.id + ','
      })
      if (userids.length > 0) {
        userids = userids.substring(0, userids.length - 1)
      }
      this.$set(scoperow, 'userids', userids)
    },
    checkEditState() {
      // 查询条件
      var params = this.getQueryParams()
      getAction(this.url.checkEditState, params)
        .then((res) => {
          if (res.success) {
            this.disableEdit = res.result
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
        .catch((err) => {})
    },
    changeEditState() {
      this.url.list = this.url.queryActivity
      this.changeState = true
      this.loadData()
      this.disableEditSubmit = false
    }
  },
  created() {
    this.visible = false
  }
}
</script>
<style scoped></style>
